<template>
  <div class='app-container app-drug'>
    <div class='container-left'>
       <!-- 药品分类 -->
       <el-tabs 
         tab-position='left'
         v-model="drugType"
         @tab-click='onTabClick'
       >
        <template v-for="(item, index) in drugTypes">
          <el-tab-pane :key="index" :label="item.text+'('+item.sum+')'" :name="item.id"/>
        </template>
       </el-tabs>
    </div>
    <div class='container-right'>
      <div class='head-container'>
        <!-- 搜索 -->
        <div v-if="crud.props.searchToggle">
          <el-select
            v-model='query.isStock'
            clearable
            size='small'
            placeholder='库存值'
            class='filter-item'
            style='width: 90px'
            @change="crud.toQuery"
          >
            <el-option
              v-for='item in stocks'
              :key='item.key'
              :label='item.text'
              :value='item.value'
            />
          </el-select>
          <el-input
            v-model='query.drugName'
            clearable
            size='small'
            placeholder='药品名称'
            style='width: 200px;'
            class='filter-item'
          />
          <el-input
            v-model='query.drugManufactor'
            clearable
            size='small'
            placeholder='生产厂家'
            style='width: 200px;'
            class='filter-item'
          />
          <el-select
            v-model='query.status'
            clearable
            size='small'
            placeholder='有效标志'
            class='filter-item'
            style='width: 90px'
            @change="crud.toQuery"
          >
            <el-option
              v-for='item in status'
              :key='item.key'
              :label='item.text'
              :value='item.value'
            />
          </el-select>
          <rrOperation :crud="crud" @resetQuery="onResetQuery" />
        </div>
        <crudOperation :permissions="permission"/>
        <!-- 表单渲染 -->
        <el-dialog 
          :width="dialogWidth"
          append-to-body 
          top="5vh"
          :close-on-click-modal="false" 
          :before-close="crud.cancelCU" 
          :visible="crud.status.cu > 0" 
          :title="dTitle"
        >
          <addEditDrug ref="form"></addEditDrug>
          <div slot="footer" class="dialog-footer">
            <el-button 
              type="text"
              @click="crud.cancelCU"
            >
            取消
            </el-button>
            <el-button 
              :loading="crud.procesLoading" 
              type="primary"
              @click="crud.submitCU($refs.form)"
            >
            确认
            </el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table 
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column v-if="columns.visible('id')" prop="id" label="药品编码">
            <template slot-scope="scope" >{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column v-if="columns.visible('drugName')" :show-overflow-tooltip="true" prop="drugName" label="商品名称" width="150px">
            <template slot-scope="scope" >{{ scope.row.drugName }}</template>
          </el-table-column>
          <el-table-column v-if="columns.visible('drugNo')" prop="drugNo" label="库位号">
            <template slot-scope="scope">
              <columnClickEdit
                :permission="['admin','drug:edit']"
                :row="scope.row" 
                :value="scope.row.drugNo"
                emptyText="无"
                @change="onChangeDrugNo"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('drugSpec')" prop="drugSpec" label="规格">
            <template slot-scope="scope" >{{ scope.row.drugSpec }}</template>
          </el-table-column>
          <el-table-column v-if="columns.visible('drugManufactor')" 
            :show-overflow-tooltip="true" prop="drugManufactor" 
            width="150px" label="生产厂家">
            <template slot-scope="scope" >{{ scope.row.drugManufactor }}</template>
          </el-table-column>
          <el-table-column v-if="columns.visible('drugType')" prop="drugType" label="药品分类">
            <template slot-scope="scope" >
						  <drugType :value="scope.row.drugType"></drugType>
					  </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('salePrice')" prop="salePrice" label="零售价">
            <template slot-scope="scope">
              <columnClickEdit
                :permission="['admin','drug:edit']"
                :value="scope.row.salePrice"
                :row="scope.row"
                @change="onChangePrice"
              >
                {{ formatMoney(scope.row.salePrice) }}
              </columnClickEdit>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('stock')" prop="stock" label="库存" width="100">
            <template slot-scope="scope">
              <template v-if="scope.row.minStock > 0">
                {{scope.row.stock + scope.row.packageUnit + scope.row.minStock + scope.row.doseUnit}}
              </template>
              <template v-else>{{scope.row.stock + scope.row.packageUnit}}</template>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('stockWarning')" prop="stockWarning" label="库存预警">
            <template slot-scope="scope">
              <columnClickEdit
                :permission="['admin','drug:edit']"
                :value="scope.row.stockWarning"
                :row="scope.row"
                @change="onChangeWarning"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('status')" label="有效标志" align="center" prop="status">
            <template slot-scope="scope">
              <template v-if="scope.row.status == 0">
                <span>正常</span>
              </template>
              <template v-if="scope.row.status == 1">
                <span>失效</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('createTime')" prop="createTime" width="140" label="创建日期">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permissions="permission"
              >
                <template slot="right">
                  <template v-if="scope.row.status === 0">
                    <el-button 
                      v-permission="['admin','drug:edit']"
                      @click="onEditStatus(scope.row)"
                      type="text" 
                    >下架</el-button>
                  </template>
                  <template v-if="scope.row.status === 1">
                    <el-button
                      v-permission="['admin','drug:edit']"
                      @click="onEditStatus(scope.row)"
                      type="text"
                    >上架</el-button>
                  </template>
                </template>
              </udOperation>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
        <!-- 弹窗 -->
        <el-dialog
          width="500px"
          append-to-body
          class="dialog-batch-operation"
          :close-on-click-modal="false"
          :visible.sync="showDialog"
          :title="dialogText"
        >
          <template v-if="batchOperation==1">
            <span>库存预警值</span>
            <el-input-number v-model="dialogForm.warnNum" />
          </template>
          <template v-if="batchOperation==2">
            <span>有效标志</span>
            <el-radio v-model="dialogForm.status" :label="0">正常</el-radio>
            <el-radio v-model="dialogForm.status" :label="1">无效</el-radio>
          </template>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :loading="dialogLoading" @click="onBatchUpdate">确认</el-button>
          </div>
        </el-dialog>
        <el-dialog
          width="600px"
          append-to-body
          :close-on-click-modal="false"
          :visible.sync="showUpdatePrice"
          title="批量调价"
        >
          <updateSalePrice 
            @cancel="showUpdatePrice=false"
            @success="onBatchUpdateSuccess"
          />
        </el-dialog>
        <el-dialog
          width="600px"
          append-to-body
          :close-on-click-modal="false"
          :visible.sync="showBatchImport"
          title="批量导入"
        >
          <batchImport 
            @cancel="showBatchImport=false"
            @success="onBatchImportSuccess"
          />
        </el-dialog>
        <drugDetail ref="drugDetail" :id="currentId" />
      </div>
    </div>
  </div>
</template>
<script>
import crudDrug,{editStatus,batchUpdateWarning,batchUpdateStatus,outDrugs} from '@/api/storageRoom/drug';
import CRUD, { presenter, header, form, crud } from '@crud/crud';
import drugPermission from "@/permission/storageRoom/drug";
import columnClickEdit from '@/components/ColumnClickEdit';
import updateSalePrice from "./module/updateSalePrice";
import crudOperation from '@crud/CRUD.operation';
import batchImport from "./module/batchImport";
import rrOperation from '@crud/RR.operation';
import udOperation from '@crud/UD.operation';
import { formatMoney } from "@/utils/index";
import pagination from '@crud/Pagination';
import drugType from "./module/drugType";
import addEditDrug from './module/add';
import drugDetail from './module/detail';

const query = { drugType: 0, isStock: "", drugName: null, drugManufactor: null, status: 0, pharmacyId: null }
const defaultCrud = CRUD({ 
  title: '库存',
  query: query, 
  hideColumns: ['id', 'drugManufactor', 'createTime'],
  url: 'drug/getDrugs',
  crudMethod: { ...crudDrug},
  queryOnPresenterCreated: false
});
const defaultForm = {};

export default {
  name: 'Drug',
  components: { 
    rrOperation,
    crudOperation,
    pagination,
    addEditDrug,
    drugDetail,
    updateSalePrice,
    batchImport,
    columnClickEdit,
    drugType,
    udOperation
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      dTitle:'新增药品',
      stocks: [
        {text: '全部', value: ""},
        {text: '有库存', value: 0},
        {text: '无库存', value: 1}
      ],
      status: [
        {text: '全部', value: ""},
        {text: '正常', value: 0},
        {text: '失效', value: 1},
      ],
      drugType: "0",
      drugTypes: [
        {id: "0", text: "全部", sum: 0}
      ],
      permission: drugPermission,
      currentId: null,
      batchOperation: 0,
      showDialog: false,
      showUpdatePrice: false,
      showBatchImport: false,
      dialogLoading: false,
      pharmacyId: null,
      dialogForm: {
        warnNum: 0,
        status: 0
      }
    };
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.query.pharmacyId = res.pharmacyId;
      this.pharmacyId = res.pharmacyId;
      this.crud.toQuery();
      this._searchType();
    });
  },
  mounted() {
    this.drugType = this.query.drugType + "";
  },
  computed: {
    dialogText() {
      if(this.batchOperation == 1) {
        return "批量修改预警值";
      } else {
        return "批量修改有效标志";
      }
    },
    dialogWidth() {
      return window.innerWidth * 0.9 + "px";
    }
  },
  methods: {
    formatMoney,
    onTabClick() {
      this.query.drugType = this.drugType;
      this.crud.toQuery();
    },
    onAdd() {
      this.crud.toAdd();
      this.$nextTick(() => {
        this.dTitle = "新增药品";
        this.$refs.form.setOperation(0);
      });
    },
    onEdit(row) {
      let data = this._clone(row);
      this.crud.toEdit(data);
      this.$nextTick(() => {
        this.dTitle = "编辑药品";
        this.$refs.form.setOperation(1, data);
      });
    },
    onEditStatus(row) {
      let data = this._clone(row);
      if(data.status === 0) {
        data.status = 1;
      } else {
        data.status = 0;
      }
      editStatus(data).then(() => {
        this._editSuccess();
      });
    },
    searchCountByDrugType() {
      let data = {
        pharmacyId: this.query.pharmacyId
      };
      crudDrug.getCountByDrugType(data).then(res => {
        res.forEach(item => {
          this.drugTypes[item.drugType].sum = item.total;
        });
      });
    },
    onShowDetails(row) {
      this.currentId = row.id;
      this.$refs.drugDetail.show = true;
    },
    onBatchOperation(operation) {
      this.batchOperation = operation;
      this.showDialog = true;
    },
    onBatchUpdate() {
      let data = [];
      let fun = batchUpdateWarning;
      let key = "warnNum";

      if(this.batchOperation == 2) {
        fun = batchUpdateStatus;
        key = "status";
      }
      this.crud.selections.forEach(item => {
        data.push({
          id: item.id,
          [key]: this.dialogForm[key]
        });
      });
      this.dialogLoading = true;
      fun(data).then(() => {
        this._editSuccess();
        this.dialogLoading = false;
        this.showDialog = false;
        this.operation = 0;
      });
    },
    onBatchUpdateSuccess() {
      this.showUpdatePrice = false;
      this.crud.toQuery();
    },
    onBatchImportSuccess() {
      this.showBatchImport=false;
      this.crud.toQuery();
      this.searchCountByDrugType();
    },
    onChangeDrugNo({row, value}) {
      let data = {
        id: row.id,
        drugNo: value
      };
      this._columnEditSubmit(0, data, row);
    },
    onChangePrice({row, value}) {
      let data = {
        id: row.id,
        salePrice: value
      };
      this._columnEditSubmit(1, data, row);
    },
    onChangeWarning({row, value}) {
      let data = [{
        id: row.id,
        warnNum: value
      }];
      this._columnEditSubmit(2, data, row);
    },
    onResetQuery() {
      this.query.pharmacyId = this.pharmacyId;
      this.drugType = "0";
    },
    onBatchImport() {
      this.showBatchImport = true;
    },
    onUpdatePrice() {
      this.showUpdatePrice = true;
    },
    onOutDrugs() {
      outDrugs(this.query);
    },
    _columnEditSubmit(type, data, row) {
      row.drugNo = data.drugNo || row.drugNo;
      row.stockWarning = data.length ? data[0].warnNum : row.stockWarning;
      row.salePrice = data.salePrice || row.salePrice;
      crudDrug.columnEdit(type, data).then(() => {
        this.crud.editSuccessNotify();
      });
    },
    _editSuccess() {
      this.crud.editSuccessNotify();
      this.crud.toQuery();
      this.searchCountByDrugType();
    },
    _clone(row) {
      let res = {};
      for(let key in row) {
        res[key] = row[key];
      }
      return res;
    },
    _searchType() {
      crudDrug.getDrugTypes().then(res => {
        res.forEach(item => {
          this.drugTypes.push({
            id: item.value,
            text: item.label,
            sum: 0
          });
        });
        this.searchCountByDrugType();
      });
    }
  }
}
</script>

<style>
.app-drug {
  display: flex;
}

.app-drug .el-table {
  overflow-x: auto;
}

.app-drug .container-left {
  width: 120px;
}

.app-drug .container-right {
  width: calc(100% - 120px);
}

.drug-info-li:not(:first-child) {
  margin-top: 10px;
}

.drug-info-li .drug-info-li-title {
  align-items: center;
  font-weight: bold;
  color: #1881dd;
  font-size: 15px;
  display: flex;
}

.drug-info-li .drug-info-li-title .el-divider {
  background-color: #1881dd;
  border-radius: 5px;
  width: 5px;
}

.add-drug {
  min-height: 450px;
}

.add-drug-tab .drug-info {
  position: relative;
}

.add-drug-tab .drug-info .drug-info-li .el-form-item {
  margin-bottom: 18px;
  margin-top: 5px;
  
}

.add-drug-tab .drug-info .drug-info-li .drug-info-inline {
  display: flex;
}

.add-drug-tab .drug-info .drug-info-li .drug-info-inline .el-form-item {
  flex-direction: column;
  display: flex;
}

.drug-info .drug-info-li .drug-info-inline .el-form-item__label {
  text-align: left;
}

.drug-info .drug-info-li .drug-info-inline .drug-info-refer {
  color: rgb(255, 132, 50); 
  font-weight: bold;
  font-size: 15px;
}

.drug-info-dropdown .el-dropdown-menu__item,
.drug-info .el-dropdown .el-dropdown-link {
  align-items: center;
  display: flex;
}

.drug-info-dropdown .el-dropdown-menu__item {
  margin-top: 5px;
}

.drug-info-dropdown .el-dropdown-menu__item img {
  margin-right: 5px;
}

.drug-info .drug-info-list {
  border: 1px solid #ebeef5;
  height: calc(100% - 42px);
  background-color: #FFF;
  position: absolute;
  border-radius: 5px;
  border-bottom: 0;
  z-index: 99;
  width: 100%;
  bottom: 0;
  left: 0;
}

.drug-info .drug-info-list .drug-info-li-title {
  position: relative;
  font-size: 18px;
  height: 40px;
}

.drug-info .drug-info-list .drug-info-li-title .drug-info-list-close {
  position: absolute;
  color: #606266;
  font-size: 26px;
  cursor: pointer;
  right: 5px;
  top: 5px;
}

.drug-info .drug-info-list .drug-list-button {
  text-align: center;
  margin-top: 10px;
  width: 100%;
}

.dialog-batch-operation .el-dialog__body {
  text-align: center;
}
</style>